package middleware

import (
	"donkey-admin/internal/consts"
	"donkey-admin/utility"
	"github.com/gogf/gf/v2/net/ghttp"
	"net/http"
)

// AuthorityHandler 权限验证拦截器
func AuthorityHandler(r *ghttp.Request) {

	token, err := utility.ParseToken(r.Context(), r.GetHeader("Authorization"))
	if err != nil {
		r.Response.WriteStatusExit(http.StatusUnauthorized)
		return
	}

	//获取请求的PATH
	obj := r.Request.URL.Path
	// 获取请求方法
	act := r.Request.Method
	// 获取用户的角色
	sub := token.UserInfo.UserRole
	e := utility.CasbinUtils.Casbin(r.Context()) // 判断策略中是否存在
	success, _ := e.Enforce(sub, obj, act)
	if !success {
		r.Response.WriteStatusExit(http.StatusForbidden)
		return
	}

	r.SetCtxVar(consts.CtxAuthorizationText, token.UserInfo)
	r.Middleware.Next()
}
